<template>
	<view class="wrap" style="padding-bottom: 60px;">
		<u-cell-group :border="false">
			<u-gap height="20" bg-color="#f5f5f5"></u-gap>
			<u-cell-item title="头像" :arrow="true">
				<u-avatar size="60" bg-color='#000;' :src="avatarUrl" @click="chooseAvatar" style="position: absolute;right: 35px;top:12px;"></u-avatar>
			</u-cell-item>
			<u-cell-item title="姓名" :value="state.name" :title-width="180" :arrow="false"></u-cell-item>
			<u-cell-item title="角色" :value="state.roleName" :title-width="180" :arrow="false"></u-cell-item>
			<u-cell-item title="手机" :value="state.phonenumber" :title-width="180" @click="navTo('/pages/sys/user/modify?item=1')"></u-cell-item>
			<u-cell-item title="邮箱" :value="state.email" :title-width="180" @click="navTo('/pages/sys/user/modify?item=2')"></u-cell-item>
			<u-cell-item title="电子签名" :arrow="true" @click="showSignature">
				<image v-if="signatureUrl" :src="signatureUrl" style="width:64px;height:28px;" mode="aspectFit" class="sign-image" />
			</u-cell-item>
			<u-cell-item title="所属单位" :value="state.deptName" :title-width="180" :arrow="false"></u-cell-item>
			<u-cell-item title="岗位" :value="state.postNames" :title-width="180" :arrow="false"></u-cell-item>
			<u-gap height="20" bg-color="#f5f5f5"></u-gap>
		</u-cell-group>
	</view>
</template>

<script>
import { filer } from '@daelui/dogjs/dist/components.js'
import uniFiler from '@/components/libs/uni-filer.js'
import ebus from '@/components/libs/ebus.js'
import { uploadAvatar, uploadSign, updateUserProfile, syncUserInfo } from '@/api/system/user.js'

// 获取用户信息
export const getUserState = function (view) {
	let user = this.getCurrentUser() || {}
	this.state = {
		id: user.id,
		name: user.nickName,
		roleName: ((user.roles ||[])[0]||{}).roleName,
		sex: user.sex,
		email: user.email,
		phonenumber: user.phonenumber,
		deptName: user.deptName,
		postNames: user.postNames
	}
	let users = this.$store.state.vuex_users
	// 同步用户信息
	return syncUserInfo(user, users, this.$u, this).then(() => {
		this.avatarUrl = user.avatarLocalPath || '/static/assets/images/head.jpg'
		this.signatureUrl = user.signLocalPath
	})
}

// 存储头像
export const storeAvatar = function (url) {
  let user = this.getCurrentUser() || {}
	let users = this.$store.state.vuex_users || []
  let userName = user.userName
  // 缓存本地的头像图片
  if (userName) {
		user.avatarLocalPath = url
		let one = users.find(item => item.userName === user.userName)
		if (one) {
			Object.assign(one, user)
		}
		this.avatarUrl = url
		this.$u.vuex('vuex_users', users)
  }
}

export default {
	data() {
		return {
			state: {
				id: '',
				name: '',
        roleName: '',
        deptName: '',
				postNames: '',
				sex: '',
				email: '',
				phonenumber: ''
			},
			rules: {},
			avatarUrl: '',
			signatureUrl: ''
		}
	},
	onLoad() {
		// 获取用户信息
    this.getUserState(this)
    // 头像剪切事件
		uni.$on('uAvatarCropper', path => {
			this.avatarPath = path
      // 存储头像
      this.storeAvatar(path)
      // 保存头像数据
      this.saveAvatar(path)
		})
    // 电子签名确认
    ebus.$off('onConfirmSignature')
    ebus.$on('onConfirmSignature', async (data) => {
			try {
				// 电子签名上传
				let path = await uniFiler.base64ToPath(data)
        let user = this.getCurrentUser()
        let users = this.$store.state.vuex_users
        users = Array.isArray(users) ? users : []
        let one = users.find(item => item.userName === user.userName)
        if (one) {
        	one.signUrl = path
        	one.signLocalPath = path
        	this.signatureUrl = path
        }
        this.$u.vuex('vuex_user', one)
        this.$u.vuex('vuex_users', users)
				data = await uploadSign({
					params: {
						filePath: path,
						name: 'signfile',
						formData: {}
					},
					vm: this
				})
				if (String(data.code) !== '200') {
					this.$u.toast('电子签名保存失败')
				}
			} catch(e) {
				this.$u.toast('电子签名保存失败')
			}
    })
		// 个人信息修改
    ebus.$off('onUpdateUser')
    ebus.$on('onUpdateUser', async (data) => {
			let user = this.getCurrentUser()
			let users = this.$store.state.vuex_users
			users = Array.isArray(users) ? users : []
			let one = users.find(item => item.userName === user.userName)
			if (one) {
				one.phonenumber = data.phonenumber
				one.email = data.email
			}
			this.$u.vuex('vuex_users', users)
			this.getUserState(this)
    })
	},
	methods: {
		getUserState,
		storeAvatar,
		navTo(url) {
			uni.navigateTo({
				url: url
			})
		},
    // 选择头像
    chooseAvatar() {
			this.$u.route({
				url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
				params: {
					destWidth: 200, // 输出图片宽高
					rectWidth: 200, // 裁剪框的宽高
					fileType: 'jpg', // 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
				}
			})
		},
		// 保存头像至服务端
    saveAvatar (url) {
		  let token = this.$store.state.vuex_token
		  if (!token) {
		    return false
		  }
		  // 查看网络状态
		  uni.getNetworkType({
		    success: (res) => {
		      if (res.networkType !== 'none') {
		        /* web */
		        if (!this.isPlus()) {
		          let file = null
		          try {
		            file = filer.base64ToFile(url)
		          } catch (e) {
		            file = null
		            console.log(e)
		          }
		          if (!file) {
		            return true
		          }
		          // 头像上传
		          uploadAvatar({
                params: {
                  file: file,
                  name: 'avatarfile',
                  formData: {},
                },
                vm: this
              }).catch(e => {
                console.log(e)
              })
		          return true
		        }

		        /* app */
		        // 头像上传
		        uploadAvatar({
              params: { filePath: url, name: 'avatarfile', formData: {} },
              vm: this,
            }).catch(e => {
		          console.log(e)
		        })
		      }
		    },
		    fail: () => {}
		  })
		},
    // 显示签名
    showSignature () {
			let user = this.getCurrentUser() || {}
      this.$store.state.signatureImage = user.signLocalPath
      this.navTo('/pages/sys/user/signature')
    },
		cancel() {
			uni.navigateBack()
		}
	}
};
</script>

<style lang="scss" scoped>
page {
  background: #f5f5f5;
}
.u-form {
  background: #fff;
  padding: 0 15px;
}
.u-size-medium{
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 20px;
	font-size:28rpx;
	background-color: rgba(0, 0, 0, 0.1);
	color:#fff;
	border: 1px solid #5186e7;
}
.u-hairline-border:after{
	border: 1px solid #5186e7!important;
}
.input-placeholder{
	text-align: right;
}
.u-input{
	text-align: right !important;
}
.u-form-item{
	font-size:36rpx;
}
</style>
